import React, { useState } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  DatePicker,
  TimePicker,
  Row,
  Col,
  Statistic,
  Progress,
  Tooltip,
  Popconfirm,
  message,
  Switch
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  PlayCircleOutlined,
  PauseCircleOutlined,
  EyeOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

interface PublishTask {
  id: string;
  title: string;
  content: string;
  images: string[];
  account: string;
  scheduledTime: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'paused';
  progress: number;
  createTime: string;
  updateTime: string;
  retryCount: number;
  maxRetries: number;
}

const Publish: React.FC = () => {
  const [tasks, setTasks] = useState<PublishTask[]>([
    {
      id: '1',
      title: '春季护肤攻略',
      content: '春季护肤的重点是补水和防晒...',
      images: ['https://via.placeholder.com/150x100'],
      account: '小红书用户1',
      scheduledTime: '2024-01-16 10:00:00',
      status: 'pending',
      progress: 0,
      createTime: '2024-01-15 14:30:00',
      updateTime: '2024-01-15 16:45:00',
      retryCount: 0,
      maxRetries: 3
    },
    {
      id: '2',
      title: '美妆产品推荐',
      content: '今天给大家推荐几款性价比超高的美妆产品...',
      images: ['https://via.placeholder.com/150x100', 'https://via.placeholder.com/150x100'],
      account: '小红书用户2',
      scheduledTime: '2024-01-16 14:30:00',
      status: 'running',
      progress: 65,
      createTime: '2024-01-14 09:20:00',
      updateTime: '2024-01-15 11:30:00',
      retryCount: 1,
      maxRetries: 3
    },
    {
      id: '3',
      title: '旅行日记分享',
      content: '这次去云南的旅行真的太美了...',
      images: ['https://via.placeholder.com/150x100'],
      account: '小红书用户1',
      scheduledTime: '2024-01-15 18:00:00',
      status: 'completed',
      progress: 100,
      createTime: '2024-01-13 16:20:00',
      updateTime: '2024-01-15 18:05:00',
      retryCount: 0,
      maxRetries: 3
    }
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingTask, setEditingTask] = useState<PublishTask | null>(null);
  const [form] = Form.useForm();

  const getStatusTag = (status: string) => {
    const statusConfig = {
      pending: { color: 'blue', text: '等待中', icon: <ClockCircleOutlined /> },
      running: { color: 'green', text: '执行中', icon: <PlayCircleOutlined /> },
      completed: { color: 'green', text: '已完成', icon: <CheckCircleOutlined /> },
      failed: { color: 'red', text: '失败', icon: <CloseCircleOutlined /> },
      paused: { color: 'orange', text: '已暂停', icon: <PauseCircleOutlined /> }
    };
    const config = statusConfig[status as keyof typeof statusConfig];
    return (
      <Tag color={config.color} icon={config.icon}>
        {config.text}
      </Tag>
    );
  };

  const getProgressColor = (status: string) => {
    if (status === 'completed') return 'green';
    if (status === 'failed') return 'red';
    if (status === 'running') return 'blue';
    return 'orange';
  };

  const columns = [
    {
      title: '任务信息',
      key: 'task',
      render: (record: PublishTask) => (
        <div>
          <div style={{ fontWeight: 'bold' }}>{record.title}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            账号: {record.account}
          </div>
        </div>
      ),
    },
    {
      title: '计划时间',
      dataIndex: 'scheduledTime',
      key: 'scheduledTime',
      render: (value: string) => (
        <div>
          <div>{dayjs(value).format('YYYY-MM-DD')}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            {dayjs(value).format('HH:mm:ss')}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: (record: PublishTask) => (
        <div>
          {getStatusTag(record.status)}
          <div style={{ marginTop: 8 }}>
            <Progress 
              percent={record.progress} 
              size="small" 
              strokeColor={getProgressColor(record.status)}
              showInfo={false}
            />
          </div>
        </div>
      ),
    },
    {
      title: '重试次数',
      key: 'retry',
      render: (record: PublishTask) => (
        <div>
          {record.retryCount}/{record.maxRetries}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (record: PublishTask) => (
        <Space>
          <Tooltip title="查看详情">
            <Button type="text" icon={<EyeOutlined />} size="small" />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          {record.status === 'pending' && (
            <Tooltip title="立即执行">
              <Button type="text" icon={<PlayCircleOutlined />} size="small" />
            </Tooltip>
          )}
          {record.status === 'running' && (
            <Tooltip title="暂停">
              <Button type="text" icon={<PauseCircleOutlined />} size="small" />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} size="small" />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingTask(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (task: PublishTask) => {
    setEditingTask(task);
    form.setFieldsValue({
      ...task,
      scheduledTime: dayjs(task.scheduledTime)
    });
    setIsModalVisible(true);
  };

  const handleDelete = (id: string) => {
    setTasks(tasks.filter(task => task.id !== id));
    message.success('任务删除成功');
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const scheduledTime = values.scheduledTime.format('YYYY-MM-DD HH:mm:ss');
      
      if (editingTask) {
        // 更新任务
        setTasks(tasks.map(task => 
          task.id === editingTask.id 
            ? { ...task, ...values, scheduledTime, updateTime: new Date().toLocaleString() }
            : task
        ));
        message.success('任务更新成功');
      } else {
        // 添加新任务
        const newTask: PublishTask = {
          id: Date.now().toString(),
          ...values,
          scheduledTime,
          status: 'pending',
          progress: 0,
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString(),
          retryCount: 0,
          maxRetries: 3
        };
        setTasks([...tasks, newTask]);
        message.success('任务创建成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const pendingTasks = tasks.filter(task => task.status === 'pending').length;
  const runningTasks = tasks.filter(task => task.status === 'running').length;
  const completedTasks = tasks.filter(task => task.status === 'completed').length;
  const failedTasks = tasks.filter(task => task.status === 'failed').length;

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="等待中"
              value={pendingTasks}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="执行中"
              value={runningTasks}
              prefix={<PlayCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成"
              value={completedTasks}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="失败"
              value={failedTasks}
              prefix={<CloseCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 任务列表 */}
      <Card
        title="发布任务管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新建任务
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={tasks}
          rowKey="id"
          pagination={{
            total: tasks.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 任务编辑模态框 */}
      <Modal
        title={editingTask ? '编辑任务' : '新建任务'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="任务标题"
                rules={[{ required: true, message: '请输入任务标题' }]}
              >
                <Input placeholder="请输入任务标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="account"
                label="发布账号"
                rules={[{ required: true, message: '请选择发布账号' }]}
              >
                <Select placeholder="请选择发布账号">
                  <Option value="小红书用户1">小红书用户1</Option>
                  <Option value="小红书用户2">小红书用户2</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="content"
            label="发布内容"
            rules={[{ required: true, message: '请输入发布内容' }]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入发布内容"
              showCount
              maxLength={1000}
            />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="scheduledTime"
                label="计划时间"
                rules={[{ required: true, message: '请选择计划时间' }]}
              >
                <DatePicker 
                  showTime 
                  format="YYYY-MM-DD HH:mm:ss"
                  style={{ width: '100%' }}
                  placeholder="请选择计划时间"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="maxRetries"
                label="最大重试次数"
              >
                <Select defaultValue={3}>
                  <Option value={1}>1次</Option>
                  <Option value={2}>2次</Option>
                  <Option value={3}>3次</Option>
                  <Option value={5}>5次</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default Publish; 